﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using System.Linq.Dynamic.Core;
using KDS.Mes.Mes.Atlas.Dtos;
using KDS.Mes.Dto;
using KDS.Mes.Authorization;
using System.Data;

#region 代码生成器相关信息_ABP Code Generator Info
//你好，我是ABP代码生成器的作者,欢迎您使用该工具，目前接受付费定制该工具，有需要的可以联系我
//我的邮箱:werltm@hotmail.com
// 官方网站:"http://www.yoyocms.com"
// 交流QQ群：104390185  
//微信公众号：角落的白板报
// 演示地址:"vue版本：http://vue.yoyocms.com angularJs版本:ng1.yoyocms.com"
//博客地址：http://www.cnblogs.com/wer-ltm/
//代码生成器帮助文档：http://www.cnblogs.com/wer-ltm/p/5777190.html
// <Author-作者>梁桐铭 ,微软MVP</Author-作者>
// Copyright © YoYoCms@China.2017-10-24T20:27:11. All Rights Reserved.
//<生成时间>2017-10-24T20:27:11</生成时间>
#endregion


namespace KDS.Mes.Mes.Atlas
{
    /// <summary>
    /// Atlas数据表服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Report_Atlass)]
    public class AtlasAppService : MesAppServiceBase, IAtlasAppService
    {
        private readonly IRepository<Atlas, int> _atlasRepository;
        private readonly IAtlasListExcelExporter _atlasListExcelExporter;


        private readonly AtlasManage _atlasManage;
        private readonly ISqlExecuter _sqlExecuter;
        /// <summary>
        /// 构造方法
        /// </summary>
        public AtlasAppService(IRepository<Atlas, int> atlasRepository,
AtlasManage atlasManage
      , IAtlasListExcelExporter atlasListExcelExporter, ISqlExecuter sqlExecuter
  )
        {
            _atlasRepository = atlasRepository;
            _atlasManage = atlasManage;
            _atlasListExcelExporter = atlasListExcelExporter;
            _sqlExecuter = sqlExecuter;
        }


        #region 实体的自定义扩展方法
        private IQueryable<Atlas> _atlasRepositoryAsNoTrack => _atlasRepository.GetAll().AsNoTracking();


        #endregion


        #region Atlas数据表管理

        public PagedResultDto<AtlasListDto> GetPagedAtlass(GetAtlasInput input)
        {
            //初步过滤
            var query = _atlasRepository.GetAll()
                        .WhereIf(!input.SeatID.IsNullOrEmpty(), u => u.SEAT_ID == input.SeatID)
                        .WhereIf(!input.StationNoId.IsNullOrEmpty(), u => u.STATION_NO == input.StationNoId)
                        .WhereIf(!input.LineId.IsNullOrEmpty(), u => u.LINE == input.LineId)
                        .WhereIf(!input.Time1.ToString().IsNullOrEmpty(), u => u.CREAT_TIME >= input.Time1)
                        .WhereIf(!input.Time2.ToString().IsNullOrEmpty(), u => u.CREAT_TIME <= input.Time2);
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderByDescending(x => x.Id) : query.OrderByDescending(t => t.CREAT_TIME);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<AtlasListDto>(tasksCount, taskList.MapTo<List<AtlasListDto>>());
        }

        /// <summary>
        /// 根据查询条件获取Atlas数据表分页列表
        /// </summary>
        public async Task<PagedResultDto<AtlasListDto>> GetPagedAtlassAsync(GetAtlasInput input)
        {

            var query = _atlasRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件

            var atlasCount = await query.CountAsync();

            var atlass = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var atlasListDtos = atlass.MapTo<List<AtlasListDto>>();
            return new PagedResultDto<AtlasListDto>(
            atlasCount,
            atlasListDtos
            );
        }

        /// <summary>
        /// 通过Id获取Atlas数据表信息进行编辑或修改 
        /// </summary>
        public async Task<GetAtlasForEditOutput> GetAtlasForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetAtlasForEditOutput();

            AtlasEditDto atlasEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _atlasRepository.GetAsync(input.Id.Value);
                atlasEditDto = entity.MapTo<AtlasEditDto>();
            }
            else
            {
                atlasEditDto = new AtlasEditDto();
            }

            output.Atlas = atlasEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取Atlas数据表ListDto信息
        /// </summary>
        public async Task<AtlasListDto> GetAtlasByIdAsync(EntityDto<int> input)
        {
            var entity = await _atlasRepository.GetAsync(input.Id);

            return entity.MapTo<AtlasListDto>();
        }







        /// <summary>
        /// 新增或更改Atlas数据表
        /// </summary>
        public async Task CreateOrUpdateAtlasAsync(CreateOrUpdateAtlasInput input)
        {
            if (input.AtlasEditDto.Id.HasValue)
            {
                await UpdateAtlasAsync(input.AtlasEditDto);
            }
            else
            {
                await CreateAtlasAsync(input.AtlasEditDto);
            }
        }

        /// <summary>
        /// 新增Atlas数据表
        /// </summary>
        public virtual async Task<AtlasEditDto> CreateAtlasAsync(AtlasEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<Atlas>();

            entity = await _atlasRepository.InsertAsync(entity);
            return entity.MapTo<AtlasEditDto>();
        }

        /// <summary>
        /// 编辑Atlas数据表
        /// </summary>
        public virtual async Task UpdateAtlasAsync(AtlasEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _atlasRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _atlasRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除Atlas数据表
        /// </summary>
        public async Task DeleteAtlasAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _atlasRepository.DeleteAsync(input.Id);
        }

        #endregion
        #region Atlas数据表的Excel导出功能


        public async Task<FileDto> GetAtlasToExcel(GetAtlasInput input)
        {
            var entities = await _atlasRepository.GetAll()
                .WhereIf(!input.SeatID.IsNullOrEmpty(), u => u.SEAT_ID == input.SeatID)
                        .WhereIf(!input.StationNoId.IsNullOrEmpty(), u => u.STATION_NO == input.StationNoId)
                        .WhereIf(!input.LineId.IsNullOrEmpty(), u => u.LINE == input.LineId)
                        .WhereIf(!input.Time1.ToString().IsNullOrEmpty(), u => u.CREAT_TIME >= input.Time1)
                        .WhereIf(!input.Time2.ToString().IsNullOrEmpty(), u => u.CREAT_TIME <= input.Time2)
                .ToListAsync();

            var dtos = entities.MapTo<List<AtlasListDto>>();

            var fileDto = _atlasListExcelExporter.ExportAtlasToFile(dtos);



            return fileDto;
        }

        //public async Task<FileDto> GetAtlasToExcel(List<AtlasListDto> lst)
        //{
        //    //var entities = await _atlasRepository.GetAll()
        //    //    //.Where(x=>x.SEAT_ID== "CE11R1709050553")        
        //    //    .ToListAsync();

        //    var dtos = lst.MapTo<List<AtlasListDto>>();

        //    var fileDto = _atlasListExcelExporter.ExportAtlasToFile(dtos);



        //    return fileDto;
        //}


        #endregion





        public List<AtlasListDto> GetAtlass(GetAtlasInput input)
        {
            //初步过滤
            var query = _atlasRepository.GetAll()
                .WhereIf(!input.LineId.IsNullOrEmpty(), u => u.LINE.Trim() == input.LineId)
                .WhereIf(!input.StationNoId.IsNullOrEmpty(), u => u.STATION_NO.Trim() == input.StationNoId)
                .WhereIf(!input.SeatTypeId.IsNullOrEmpty(), u => u.SEAT_ID.Substring(0, 1) == input.SeatTypeId)
                .WhereIf(!input.Time1.ToString().IsNullOrEmpty(), u => u.CREAT_TIME >= input.Time1)
                .WhereIf(!input.Time2.ToString().IsNullOrEmpty(), u => u.CREAT_TIME <= input.Time2)
                .Where(x => x.TORQUE != null && x.TORQUE != "" && x.TIGHTENING_STATUS == "1");
            //排序
            //query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderByDescending(x => x.Id) : query.OrderByDescending(t => t.CREAT_TIME);
            //获取总数
            //var tasksCount = query.Count();
            ////默认的分页方式
            ////var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            ////ABP提供了扩展方法PageBy分页方式
            //var taskList = query.PageBy(input).ToList();
            return query.MapTo<List<AtlasListDto>>();
        }




    }
}
